<template>
  <div class="h-full">
    <vxe-card title="" class="w-full" :border="false">
      <div class="flex items-center">
        <div class="border-arrow" @click="toPrevPage">
          <FontIcon icon="icon-left" />
        </div>
        <div class="text-[#242930] ml-4">
          <span class="text-[--autata-font-gray-color]">分组名称：</span>
          {{ getParameter.name }}
        </div>
      </div>
    </vxe-card>

    <div
      class="bg-white h-full rounded-[2px] overflow-hidden px-[16px] mt-[16px]"
    >
      <vxe-toolbar ref="toolbarRef">
        <template #tools>
          <el-button
            type="primary"
            class="my-[0.5em]"
            plain
            @click="getGroupTableList"
            >刷新
          </el-button>
        </template>
      </vxe-toolbar>

      <vxe-table
        ref="tableRef"
        :column-config="{ resizable: false }"
        :expand-config="expandConfig"
        :row-config="{ isHover: true }"
        :loading="loading"
        :data="tableData"
        @toggle-tree-expand="toggleExpandChangeEvent"
      >
        <vxe-column type="expand" width="60">
          <template #content="{ row }">
            <div class="p-[16px] bg-[#F5F9FF] device-table">
              <el-table :data="row.deviceData" :border="false">
                <el-table-column label="设备编码" prop="device_id" />
                <el-table-column label="门店名称" prop="store_name" />
                <el-table-column label="设备状态" prop="device_status">
                  <template #default="{ row }">
                    <el-tag :type="formatStatusText(row).status"
                      >{{ formatStatusText(row).text }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  label="激活/锁机时间"
                  prop="activation_time"
                  :width="190"
                />
              </el-table>
            </div>
          </template>
        </vxe-column>
        <vxe-column title="门店名称" align="center" field="name" />
        <vxe-column title="设备数量" align="center" field="device_num" />
        <vxe-column
          title="门店状态"
          align="center"
          field="store_status"
          :formatter="({ cellValue }) => (cellValue ? '已撤店' : '经营中')"
        />
        <vxe-column title="创建时间" align="center" field="create_time" />
      </vxe-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import {
  VxeTableInstance,
  VxeTableEvents,
  VxeToolbarInstance,
  VxeTablePropTypes
} from "vxe-table";
import { getStoreList, StoreProp } from "@/api/teaInfuser/store";
import { deviceGetList, DeviceProp } from "@/api/teaInfuser/device";
import { useDetail } from "./hooks";
import { useGlobal } from "@pureadmin/utils";
import { onBeforeRouteLeave, useRouter } from "vue-router";
import { emitter } from "@/utils/mitt";

const { getParameter } = useDetail();
const { $storage } = useGlobal<GlobalPropertiesApi>();
const router = useRouter();

const tableRef = ref<VxeTableInstance<StoreProp>>();
const toolbarRef = ref<VxeToolbarInstance>();

const loading = ref(false);
const tableData = ref<StoreProp[]>([]);

const expandConfig = reactive<VxeTablePropTypes.ExpandConfig<StoreProp>>({
  trigger: "row",
  lazy: true,
  async loadMethod({ row }) {
    const res = await deviceGetList({
      start_page: 1,
      size: 0,
      store_id: row.id
    });
    row.deviceData = res.data;
  }
});

const toPrevPage = () => {
  router.go(-1);
};

const toggleExpandChangeEvent: VxeTableEvents.ToggleTreeExpand = params => {
  const $table = tableRef.value;
  if ($table) {
    const { row, expanded } = params;
    console.log(
      "节点展开事件",
      expanded,
      "获取父节点：",
      $table.getParentRow(row)
    );
  }
};

const getGroupTableList = async () => {
  loading.value = true;
  try {
    const res = await getStoreList({
      start_page: 1,
      size: 0,
      group_idlist: JSON.stringify([{ group_id: getParameter.id }])
    });
    tableData.value = res.data;
    loading.value = false;
  } catch (e) {
    tableData.value = [];
    loading.value = false;
  }
};

type status = "success" | "warning" | "info" | "primary" | "danger";

function formatStatusText(row: DeviceProp): {
  text: string;
  status: status;
} {
  let text = "",
    status: status = "success";
  if (row.device_status === 0 && row.store_id != null) {
    text = "正常";
    status = "success";
  } else if (row.store_id === null) {
    text = "未激活";
    status = "info";
  } else if (row.device_status === 1) {
    text = "锁机";
    status = "danger";
  }
  return {
    text,
    status
  };
}

function storageConfigureChange<T>(key: string, val: T): void {
  const storageConfigure = $storage.configure;
  storageConfigure[key] = val;
  // $storage.configure = storageConfigure;
}

onMounted(() => {
  getGroupTableList();

  const $table = tableRef.value;
  const $toolbar = toolbarRef.value;
  if ($table && $toolbar) {
    $table.connect($toolbar);
  }
  // storageConfigureChange("hideTabs", true);
  // emitter.emit("tagViewsChange", true as unknown as string);
});

// onBeforeRouteLeave((to, from, next) => {
//   storageConfigureChange("hideTabs", false);
//   emitter.emit("tagViewsChange", false as unknown as string);
//   next();
// });
</script>

<style lang="scss" scoped>
.device-table {
  :deep(table) {
    background: #f5f9ff !important;
  }

  :deep(.el-table th.el-table__cell) {
    background: #f5f9ff;
  }

  :deep(.el-table tr) {
    background: #f5f9ff;
  }
}
</style>
